
package com.biz.primus.ms.commodity.service.backend;


import com.biz.primus.base.enums.ExtendType;
import com.biz.primus.base.exception.utils.AssertUtils;
import com.biz.primus.base.vo.ProductFieldItemVo;
import com.biz.primus.base.vo.ProductFieldVo;
import com.biz.primus.commodity.exception.CommodityExceptionType;
import com.biz.primus.commodity.vo.ExtendDetailVo;
import com.biz.primus.commodity.vo.ExtendQueryVo;
import com.biz.primus.commodity.vo.ExtendVo;
import com.biz.primus.common.utils.CopyUtils;
import com.biz.primus.common.utils.JsonUtils;
import com.biz.primus.common.vo.SpringPageVO;
import com.biz.primus.ms.base.vo.SpringPageToSpringPageVO;
import com.biz.primus.ms.commodity.dao.po.Category;
import com.biz.primus.ms.commodity.dao.po.Extend;
import com.biz.primus.ms.commodity.dao.redis.extend.ExtendRedisDao;
import com.biz.primus.ms.commodity.dao.repository.category.CategoryRepository;
import com.biz.primus.ms.commodity.dao.repository.product.ExtendRepository;
import com.biz.primus.ms.commodity.dao.ro.ExtendRo;
import com.biz.primus.ms.commodity.dao.specification.ExtendSpecification;
import com.biz.primus.ms.commodity.trans.Extend2ExtendDetailVo;
import com.biz.primus.ms.commodity.trans.Extend2ExtendRo;
import com.google.common.collect.Lists;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Objects;

/**
 * @author 江南
 * @usage
 * @reviewer
 */
@Slf4j
@Service
public class ExtendService extends AbstractBrandService {

    @Autowired
    private ExtendRepository extendRepository;

    @Autowired
    private ExtendRedisDao extendRedisDao;

    @Autowired
    private CategoryRepository categoryRepository;

    /**
     * 后台功能
     */

    @Transactional(rollbackFor = Exception.class)
    public void createExtend(ExtendVo extendVo) {
        Extend extend = new Extend();
        CopyUtils.copyProperties(extendVo, extend);
        Category category = categoryRepository.findOne(Long.valueOf(extendVo.getCategoryId()));
        AssertUtils.notNull(category, CommodityExceptionType.CATEGORY_NOT_FOUND);
        extend.setCategoryId(extend.getCategoryId());
        extend.setOption(JsonUtils.obj2Json(extendVo.getOptions()));
        extend.setId(idService.getNextId());
        extendRepository.save(extend);
        this.delayer.executeAfterTransactionCommit(() -> {
            ExtendRo extendRo = new Extend2ExtendRo().apply(extend);
            extendRedisDao.save(extendRo);
        });
    }

    @Transactional(rollbackFor = Exception.class)
    public void updateExtend(Long extendId, ExtendVo extendVo) {
        Extend extend = extendRepository.getOne(extendId);
        CopyUtils.copyProperties(extendVo, extend);
        Category category = categoryRepository.findOne(Long.valueOf(extendVo.getCategoryId()));
        AssertUtils.notNull(category, CommodityExceptionType.CATEGORY_NOT_FOUND);
        extend.setOption(JsonUtils.obj2Json(extendVo.getOptions()));
        extendRepository.save(extend);
        this.delayer.executeAfterTransactionCommit(() -> {
            ExtendRo extendRo = new Extend2ExtendRo().apply(extend);
            extendRedisDao.save(extendRo);
        });
    }

    public void delExtend(Long extendId, String delUser) {
        log.info("DELETE EXTEND id = {},user = {}", extendId, delUser);
        Extend extend = extendRepository.findOne(extendId);
        String key = extend.getKey();
        AssertUtils.notNull(extend, CommodityExceptionType.COMMON_EXCEPTION, "删除项不存在");
        extendRepository.delete(extend);
        this.delayer.executeAfterTransactionCommit(() -> {
            extendRedisDao.delete(key);
        });
    }

    public SpringPageVO<ExtendDetailVo> findExtends(ExtendQueryVo queryVo) {
        PageRequest pageRequest = queryVo.toPageRequest();
        Page<Extend> page = extendRepository.findAll(new ExtendSpecification(queryVo), pageRequest);
        return SpringPageToSpringPageVO.of(page, new Extend2ExtendDetailVo());
    }

    public ExtendDetailVo findExtendById(Long extendId) {
        Extend extend = extendRepository.findOne(extendId);
        AssertUtils.notNull(extend, CommodityExceptionType.COMMON_EXCEPTION, "没有找到extend");
        return new Extend2ExtendDetailVo().apply(extend);
    }

    /**
     * 前台功能
     * 通过分类Id 获取筛选条件(注:扩展属性类型为手动输入的 不返回)
     */
    public List<ProductFieldVo> findFieldByCategoryId(Long categoryId) {
        List<ExtendRo> extendRos = extendRedisDao.findExtends(categoryId);
        List<ProductFieldVo> respVos = Lists.newArrayList();
        extendRos.stream()
                .filter(Objects::nonNull)
                .filter((p) -> Objects.equals(p.getExtendType(), ExtendType.OPTION))
                .forEach((p) -> {
                    ProductFieldVo productFieldVo = new ProductFieldVo();
                    productFieldVo.setField(p.getKey());
                    productFieldVo.setLabel(p.getLabel());
                    List<ProductFieldItemVo> itemVos = Lists.newArrayList();
                    p.getOptions().stream().filter(Objects::nonNull).forEach((item)->itemVos.add(new ProductFieldItemVo(item.getValue(),p.getKey())));
                    productFieldVo.setItems(itemVos);
                    respVos.add(productFieldVo);
                });
        return respVos;
    }
}